package com.yuyu.demo.demo_springboot.handle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yuyu.demo.demo_springboot.domain.Result;
import com.yuyu.demo.demo_springboot.exception.GirlException;
import com.yuyu.demo.demo_springboot.utils.ResultUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义异常处理类
 * 1. 自定义异常继承Exception类
 * 2. 使用@ControllerAdvice来注解Handler
 *
 */
@ControllerAdvice
public class ExceptionHandle {
	
	private final static Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);
	
	@ExceptionHandler(value=Exception.class)
	@ResponseBody
	public Result handle(Exception exception){
		if (exception instanceof GirlException) {
			GirlException girlException = (GirlException) exception;
			return ResultUtil.error(girlException.getCode(), girlException.getMessage());
		}else {
			logger.error("[系统异常] {}",exception);
			return ResultUtil.error(-1, exception.getMessage());
		}
	}

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public Result jsonExceptionHandler(Exception e,HttpServletRequest request) {
		request.setAttribute("errorMsg",e.getMessage());
		return ResultUtil.error(-1, e.getMessage());
	}
}
